<template>
	<view class="content">
		<map class="positFemr" show-location :latitude="latitude" :longitude="longitude" scale="15" :markers="markers"
			:polyline="polyline" @regionchange="regionchange" @callouttap="navigation" @markertap="markertaptap"
			@tap="tapMap">
		</map>
		<view class="body-button">
			<button v-if="!isStart" size="default" type="primary" style="color:#ffffff;" hover-class="start"
				@click="locationStart()">开始</button>
			<!-- <button v-if="isShowPause && isPause" size="default" type="primary" style="color:#ffffff;"
				hover-class="start" @click="locationStart()">暂停</button>
			<button v-if="isShowPause && !isPause" size="default" type="primary" style="color:#ffffff;"
				@click="locationStop()">继续</button> -->
			<button v-if="isStart" size="default" type="primary" style="color:#ffffff;" @click="clickStop()">结束</button>

			<!-- <button style="margin-left: 30rpx;color:#ffffff;" size="default" type="primary"
				@click="startNotifi()">保活</button> -->

			<button style="margin-left: 30rpx;color:#ffffff;" size="default" type="primary"
				@click="cliarData()">清空</button>
			<button style="margin-left: 30rpx;color:#ffffff;" size="default" type="primary"
				@click="openDebug()">调试</button>
		</view>
		<view style="clear: both;"></view>
		<view class="bottom-text">
			<view>距离：{{distance}} KM </view>
			<view>耗时：{{timeConsuming}} s </view>
			<view>时速： {{speed}} km/h </view>
			<view>
				<span v-if="start_time>0">{{formatTimestamp(start_time)}}</span>
				<span v-if="start_time>0 && stop_time>0"> - {{formatTimestamp(stop_time)}}</span>
			</view>
			<view class="localModel">
				<view class="">定位模式：</view>
				<view v-for="(i, index) in localModelList" :key="index" @click="changeys(index)"
					:class="['w_25', localModelId == index ? 'yscss' : 'w_25']">{{ i }}</view>
			</view>
			<view class="" v-if="errorList.length>0">
				<view class="">异常数据：</view>
				<view v-for="(i, index) in errorList" :key="index">{{ i }}</view>
			</view>
		</view>
	</view>
</template>

<script>
	import NotifiUtil from '@/notification/notification.js';
	import menghnMap from '@/components/menghn-map/menghn-map';
	export default {
		components: {
			menghnMap
		},
		data() {
			return {
				localtionCount: 0,
				localModelId: 1,
				localModelList: ["持续", "单次"],
				debugStatus: false,
				errorList: [],
				isStart: false,
				gpsTimer: null,
				timeTimer: null,
				start_time: 0,
				stop_time: 0,
				distance: 0,
				timeConsuming: 0,
				speed: 0,
				start_loc: {},
				latitude: 0,
				longitude: 0,
				scrollTimer: null,
				showOper: false,
				markers: [],
				polyline: [{
					points: [],
					color: "#ff00ff"
				}]
			}
		},
		onLoad() {
			//this.locationToKm(33.62164, 114.639084, 33.61998, 114.644433);
		},
		methods: {
			openDebug() {
				this.debugStatus = true;
				this.localtionCount = 0;
			},
			changeys(index) {
				console.log("切换定位模式:", this.localModelList[index], "定位");
				this.localModelId = index;
				this.openLocation();
			},
			cliarData() {
				this.clickStop();
				this.distance = 0;
				this.timeConsuming = 0;
				this.speed = 0;
				this.start_time = 0;
				this.errorList = [];
				this.debugStatus = false;
			},
			startNotifi() {
				var appname = '实时轨迹';
				var NotificationUtil = NotifiUtil(); //实例创建
				NotificationUtil.setNotification(appname, "开始下载! ");
				NotificationUtil.setProgress(20, appname);
			},
			// 将时间戳转换成指定格式（yyyy-MM-dd HH:mm:ss）
			formatTimestamp(timestamp) {
				var dateObj = new Date(timestamp); // 创建一个新的Date对象
				var year = dateObj.getFullYear().toString(); // 获取年份并转换为字符串类型
				var month = (dateObj.getMonth() + 1).toString().padStart(2, '0'); // 获取月份并补全两位数
				var day = dateObj.getDate().toString().padStart(2, '0'); // 获取天数并补全两位数
				var hours = dateObj.getHours().toString().padStart(2, '0'); // 获取小时并补全两位数
				var minutes = dateObj.getMinutes().toString().padStart(2, '0'); // 获取分钟并补全两位数
				var seconds = dateObj.getSeconds().toString().padStart(2, '0'); // 获取秒数并补全两位数

				return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`; // 返回格式化后的结果
			},
			locationToKm(lat1, lon1, lat2, lon2) {
				if (lat1 == 0 && lon1 == 0) {
					return 0;
				}
				if (lat2 == 0 && lon2 == 0) {
					return 0;
				}
				// var La1 = lat1 * Math.PI / 180.0;
				// var La2 = lat2 * Math.PI / 180.0;
				// var La3 = La1 - La2;
				// var Lb3 = lon1 * Math.PI / 180.0 - lon2 * Math.PI / 180.0;
				// var s = 2.0 * Math.asin(Math.sqrt(Math.pow(Math.sin(La3 / 2.0), 2.0) + Math.cos(La1) * Math.cos(La2) * Math.pow(
				// 	Math.sin(Lb3 / 2.0), 2.0)));
				// s = s * 6378.137;
				//s = s.toFixed(6);
				var R = 6378100; // 地球平均半径（单位：米）
				var dLat = this.toRad(lat2 - lat1);
				var dLon = this.toRad(lon2 - lon1);
				var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
					Math.cos(this.toRad(lat1)) * Math.cos(this.toRad(lat2)) *
					Math.sin(dLon / 2) * Math.sin(dLon / 2);
				var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
				var s = (R * c / 1000.0).toFixed(3);
				console.log("计算距离: ", s, " km");
				return s;
			},
			toRad(d) {
				return d * Math.PI / 180;
			},
			openLocation() {
				let that = this;
				if (!this.isStart) {
					return;
				}
				console.log('uni.getLocation');
				that.locationStop();
				//清空定位
				if (that.localModelId == 1) {
					if (!that.gpsTimer) {
						that.gpsTimer = setInterval(function() {
							uni.getLocation({
								type: 'gcj02',
								success: function(res) {
									that.updateLocaltion(res);
								}
							})
						}, 3000);
					}
					uni.getLocation({
						type: 'gcj02',
						success: function(res) {
							that.updateLocaltion(res);
						}
					})
				}
				if (that.localModelId == 0) {
					uni.startLocationUpdate({
						type: 'gcj02',
						success: function(res) {
							console.log('startLocationUpdate success:', res);
						}
					});
					// 监听实时定位变化
					uni.onLocationChange((res) => {
						that.updateLocaltion(res);
					});
				}
			},
			updateLocaltion(res) {
				let that = this;
				if (that.lat_start == "") {
					//记录第一次获取到的经纬度
					that.start_loc.lon_start = res.longitude;
					that.start_loc.lat_start = res.latitude;
				}
				if (this.localtionCount == 0 && this.debugStatus) {
					res.latitude = 33.620129;
					res.longitude = 114.642445;
				}
				let distance;
				if ((that.longitude == 0 && that.latitude == 0) || that.longitude != res.longitude) {
					distance = that.locationToKm(res.latitude, res.longitude, that.latitude, that.longitude);
					that.longitude = res.longitude;
					that.latitude = res.latitude;
					that.markers.push({
						latitude: res.latitude,
						longitude: res.longitude,
						iconPath: '../../static/dwicon.png',
					});
					that.polyline[0].points.push({
						latitude: res.latitude,
						longitude: res.longitude
					});
				}
				distance = parseFloat(distance);
				if (distance > 0.0001 && distance < 0.72) {
					that.distance += distance;
					that.speed = (that.distance / that.timeConsuming * 60 * 60).toFixed(2);
				} else {
					this.errorList.push(distance + "km," + res.latitude + "," + res.longitude);
				}
				this.localtionCount++;
				//console.log(JSON.stringify(this.$data));
			},
			locationStart() {
				let that = this;
				that.isStart = true;
				that.isShowPause = true;
				that.isPause = true;
				that.start_time = Date.now();
				that.beforeExport();
				that.openLocation();
				if (!that.timeTimer) {
					that.timeTimer = setInterval(function() {
						that.timeConsuming = (Date.now() - that.start_time) / 1000.00;
					}, 100);
				}

			},
			// 6.5*60*24 = 9360  距离
			// 9360 / 24 / 60 = 6.5m/s
			// 9360 / 24 / 60 * 60 * 60 = 23.4 km/h
			clickStop() {
				let that = this;
				that.locationStopTime();
				that.locationStop();
			},
			locationStop() {
				let that = this;
				uni.stopLocationUpdate();
				if (that.gpsTimer) {
					clearInterval(that.gpsTimer);
					that.gpsTimer = null;
				}
				if (that.timeTimer) {
					clearInterval(that.timeTimer);
					that.timeTimer = null;
				}
			},
			locationStopTime() {
				let that = this;
				that.isStart = false;
				that.isShowPause = false;
				that.isPause = false;
				that.stop_time = Date.now();
			},
			beforeExport() {
				// 判断有没有权限
				var _this = this
				plus.android.requestPermissions(['android.permission.ACCESS_FINE_LOCATION'], function(e) {
					if (e.deniedAlways.length > 0) { //权限被永久拒绝
						// 弹出提示框解释为何需要读写手机权限，引导用户打开设置页面开启
						uni.showModal({
							title: '定位权限',
							content: '您拒绝了定位权限，请前往设置-应用开启权限。',
							success: function(res) {
								if (res.confirm) {
									// console.log('用户点击确定');
								} else if (res.cancel) {
									// console.log('用户点击取消');
								}
							}
						});
					}
					if (e.deniedPresent.length > 0) { //权限被临时拒绝
						// 弹出提示框解释为何需要读写手机权限，可再次调用plus.android.requestPermissions申请权限
						plus.android.requestPermissions(['android.permission.ACCESS_FINE_LOCATION'])

					}

				}, function(e) {

				});
			},
			regionchange(e) { //移动地图触发
				if (this.scrollTimer != null) { //节流
					clearTimeout(this.scrollTimer);
				}
				this.scrollTimer = setTimeout(() => {
					if (e.type == 'end' && e.causedBy == 'drag') {
						console.log('地图移动了');
					}
				}, 500)
			},
			navigation(e) {
				console.log('navigation');
			},
			markertaptap(e) {
				console.log('markertaptap');
			},
			tapMap(e) { //点击地图触发
				this.showOper = !this.showOper;
				console.log('tapMap');
			}

		}
	}
</script>

<style scoped>
	.localModel {
		height: 90rpx;
		line-height: 63rpx;
		display: flex;
		width: 100%;
		text-align: center;
	}

	.w_25 {
		width: 15%;
		background-color: #fff;
		color: #007aff;
		border-radius: 30rpx;
	}

	.yscss {
		background-color: #007aff;
		color: #fff;
	}

	.delShow {
		position: absolute;
		top: ;
	}

	.positFemr {
		width: 100%;
		height: 60vh;
	}

	.body-button {
		margin-top: 30rpx;
		padding-left: 25%;
	}

	.body-button button {
		width: 23%;
		float: left;
	}

	.body-button .stop {
		margin-left: 10%;
	}

	.bottom-text {
		margin: 30rpx 0 0 70rpx;
	}

	.bottom-text view {
		margin-bottom: 30rpx;
	}
</style>